package chapter_1.tcp_test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 创建一个TCP通信的客户端
 * @author fulv
 */
public class TCPClient {
    public static void main(String[] args) {
        //首先输入要连接的服务器的ip地址和端口号
        Scanner sc = new Scanner(System.in);
        String addr = "";
        Integer port = 0;
        System.out.println("输入连接的服务器主机名或者ip地址: ");
        if(sc.hasNextLine()){
            addr = sc.nextLine();
        }
        System.out.println("输入连接的服务器端口号:");
        if(sc.hasNextLine()){
            port = sc.nextInt();
        }

        //建立连接服务器的套接字
        Socket socket = null;
        try {
            socket = new Socket(addr, port);
            if(socket.isConnected()){
                System.out.println("成功连接服务器");
                System.out.println("端口号: " + socket.getLocalPort());
            }

            //获取用于发送和接收数据的输入输出流
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();

            //向服务器发送数据(数据是字节数组形式的)
            String data = "China你好中国! Hello World";
            //将字符串转换为字节数组
            byte[] sendData = data.getBytes(StandardCharsets.UTF_8);
            out.write(sendData);


            socket.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }



}
